package com.aniu.smslisten;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.aniu.smslisten.service.SmsListenService;
import com.aniu.smslisten.util.LogToFile;

import java.util.ArrayList;
import java.util.HashSet;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private static final int LOCATION_PERMISSION_REQUEST_CODE = 5;
    private static final int RECEIVE_SMS_PERMISSION_REQUEST_CODE = 2;
    private static final int VIBRATE_PERMISSION_REQUEST_CODE = 3;
    private static final int POST_NOTIFICATIONS_PERMISSION_REQUEST_CODE = 4;
    private ListView listView;
    private EditText editText;
    private Button addButton;
    private Button removeButton;
    private Button resetButton;
    private ArrayAdapter<String> adapter;
    private ArrayList<String> specificContents;
    private SharedPreferences sharedPreferences;
    private TextView permissionPromptTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        LogToFile.log(this, TAG, "MainActivity onCreate called");

        // 初始化SharedPreferences
        sharedPreferences = getSharedPreferences("SmsListenPrefs", MODE_PRIVATE);
        specificContents = new ArrayList<>(sharedPreferences.getStringSet("specificContents", new HashSet<String>() {{
            add("立即驶离");
        }}));

        // 初始化UI元素
        listView = findViewById(R.id.listViewSpecificContents);
        editText = findViewById(R.id.editTextSpecificContent);
        addButton = findViewById(R.id.buttonAdd);
        removeButton = findViewById(R.id.buttonRemove);
        resetButton = findViewById(R.id.buttonReset);
        permissionPromptTextView = findViewById(R.id.textViewPermissionPrompt);

        adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, specificContents);
        listView.setAdapter(adapter);

        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String newContent = editText.getText().toString().trim();
                if (!newContent.isEmpty()) {
                    specificContents.add(newContent);
                    adapter.notifyDataSetChanged();
                    saveSpecificContents();
                    editText.setText("");
                }
            }
        });

        removeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = listView.getCheckedItemPosition();
                if (position != ListView.INVALID_POSITION) {
                    specificContents.remove(position);
                    adapter.notifyDataSetChanged();
                    saveSpecificContents();
                }
            }
        });

        resetButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                specificContents.clear();
                specificContents.add("立即驶离");
                adapter.notifyDataSetChanged();
                saveSpecificContents();
            }
        });

        // 检查并请求权限
        checkAndRequestPermissions();

        // 设置textViewPermissionPrompt的可见性
        permissionPromptTextView.setVisibility(View.VISIBLE);
    }

    private void checkAndRequestPermissions() {
        ArrayList<String> permissionsToRequest = new ArrayList<>();

        // 检查并请求RECEIVE_SMS权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECEIVE_SMS) != PackageManager.PERMISSION_GRANTED) {
            permissionsToRequest.add(Manifest.permission.RECEIVE_SMS);
        }

        // 检查并请求VIBRATE权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.VIBRATE) != PackageManager.PERMISSION_GRANTED) {
            permissionsToRequest.add(Manifest.permission.VIBRATE);
        }

        // 检查并请求POST_NOTIFICATIONS权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
            permissionsToRequest.add(Manifest.permission.POST_NOTIFICATIONS);
        }

        // 检查并请求FOREGROUND_SERVICE_LOCATION权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.FOREGROUND_SERVICE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            permissionsToRequest.add(Manifest.permission.FOREGROUND_SERVICE_LOCATION);
        }

        // 检查并请求ACCESS_COARSE_LOCATION权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            permissionsToRequest.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        }

        // 一次性请求所有需要的权限
        if (!permissionsToRequest.isEmpty()) {
            ActivityCompat.requestPermissions(this, permissionsToRequest.toArray(new String[0]), POST_NOTIFICATIONS_PERMISSION_REQUEST_CODE);
        } else {
            registerSmsReceiver();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean allPermissionsGranted = true;
        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                allPermissionsGranted = false;
                break;
            }
        }
        if (!allPermissionsGranted) {
            Toast.makeText(this, "权限申请被拒绝. 退出应用.", Toast.LENGTH_SHORT).show();
            finish(); // 退出应用
        } else {
            registerSmsReceiver();
        }
    }

    private void registerSmsReceiver() {
        LogToFile.log(this, TAG, "Registering SmsReceiver");
        Intent serviceIntent = new Intent(this, SmsListenService.class);
        startForegroundService(serviceIntent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LogToFile.log(this, TAG, "MainActivity onDestroy called");
        LogToFile.log(this, TAG, "SmsListenService stopped from MainActivity");
    }

    private void saveSpecificContents() {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putStringSet("specificContents", new HashSet<>(specificContents));
        editor.apply();
    }

    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        if (connectivityManager != null) {
            NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
            return activeNetwork != null && activeNetwork.isConnected();
        }
        return false;
    }
}
